﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using NETCONLib;
using System.Net.NetworkInformation;
using System.ServiceProcess;

/// <summary>
/// 主要目标功能实现本地网络共享：Wi-Fi 【现在仅仅用于Win7系统带有无线功能的的电脑】
/// 执行CMD命令 共享本地网络 等辅助类 
/// tang 2013-7-18
/// </summary>
public class ComSubHelper
{
    /// <summary>
    /// 执行多条CMd语句
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
    public static string ExecuteCmd(params object[] args)
    {
        string output = "";
        try
        {
            Process p = new Process();
            p.StartInfo = new ProcessStartInfo("CMD");
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.Start();
            p.StandardInput.WriteLine("C:");
            //p.StandardInput.WriteLine(@"cd windows\system32");
            foreach (var item in args)
            {
                p.StandardInput.WriteLine(item.ToString());
            }
            p.StandardInput.WriteLine("exit");
            output = p.StandardOutput.ReadToEnd();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        return output;
    }
    /// <summary>
    /// 执行  CMD Dos命令语句 
    /// </summary>
    /// <param name="dosCommand">cmd语句</param>
    /// <returns></returns>
    public static string ExecuteCmd(string dosCommand)
    {
        return Execute(dosCommand, 10);
    }
    /// <summary>  
    /// 执行DOS命令，返回DOS命令的输出  
    /// </summary>  
    /// <param name="dosCommand">dos命令</param>  
    /// <param name="milliseconds">等待命令执行的时间（单位：毫秒），  
    /// 如果设定为0，则无限等待</param>  
    /// <returns>返回DOS命令的输出</returns>  
    private static string Execute(string command, int seconds)
    {
        string output = ""; //输出字符串  
        if (command != null && !command.Equals(""))
        {
            Process process = new Process();//创建进程对象  
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "cmd.exe";//设定需要执行的命令  
            startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出  
            startInfo.UseShellExecute = false;//不使用系统外壳程序启动  
            startInfo.RedirectStandardInput = false;//不重定向输入  
            startInfo.RedirectStandardOutput = true; //重定向输出  
            startInfo.CreateNoWindow = true;//不创建窗口  
            process.StartInfo = startInfo;
            try
            {
                if (process.Start())//开始进程  
                {
                    if (seconds == 0)
                    {
                        process.WaitForExit();//这里无限等待进程结束  
                    }
                    else
                    {
                        process.WaitForExit(seconds); //等待进程结束，等待时间为指定的毫秒  
                    }
                    output = process.StandardOutput.ReadToEnd();//读取进程的输出  
                }
            }
            catch
            {
            }
            finally
            {
                if (process != null)
                    process.Close();
            }
        }
        return output;
    }

    /// <summary>
    /// 共享网络连接
    /// NetSharingManager先添加项目引用，选“浏览”，添加"C:\Windows\System32\"目录下的hnetcfg.dll，
    /// </summary>
    /// <param name="toShare">被共享的网络连接</param>
    /// <param name="forConnectioin">需要共享的网络连接</param>
    public static void ShareNetwork(string toShare, string forConnectioin)
    {
        try
        {
            string connectionToShare = toShare;// "本地连接"; // 被共享的网络连接
            string sharedForConnection = forConnectioin; //"无线网络连接2"; // 需要共享的网络连接
            NetSharingManager manager = new NetSharingManager();
            var connections = manager.EnumEveryConnection;
            foreach (INetConnection item in connections)
            {
                var props = manager.NetConnectionProps[item];
                var sharingCfg = manager.INetSharingConfigurationForINetConnection[item];
                if (props.Name == connectionToShare)
                {
                    sharingCfg.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PUBLIC);
                }
                else if (props.Name == sharedForConnection)
                {
                    sharingCfg.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PRIVATE);
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("请打开网络和共享中心，查看是不是已经连接Internet！\n" + ex.Message);
        }
    }

    /// <summary>
    /// NetworkInterface 引用 using System.Net.NetworkInformation; 
    /// 返回本地网络连接信息 名称集合（如：本地连接）
    /// </summary>
    /// <returns>如果无则返回 长度为0的空集合</returns>
    public static string[] GetLocalNetworkInformation()
    {
        List<string> localNetworkList = new List<string>();
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//返回描述本地计算机上的网络接口的对象。
        foreach (NetworkInterface item in adapters)
        {
            localNetworkList.Add(item.Name);
        }
        return localNetworkList.ToArray();
    }

    /// <summary>
    ///引用 using System.ServiceProcess;
    /// 判断window服务是否存在
    /// </summary>
    /// <param name="serviceName">服务名称</param>
    /// <returns></returns>
    private static bool ServiceExisted(string serviceName)
    {
        bool b = false;
        ServiceController[] services = ServiceController.GetServices();
        foreach (ServiceController item in services)
        {
            if (item.ServiceName == serviceName)
            {
                b = true;
                break;
            }
        }
        return b;
    }
    /// <summary>
    /// 启动window 服务
    /// </summary>
    /// <param name="serviceName">需要启动的服务名称</param>
    public static void StartService(string serviceName)
    {
        if (ServiceExisted(serviceName))//判断服务存在不
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
                {
                    service.Start();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == ServiceControllerStatus.Running)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            throw new Exception("无法启动" + serviceName + "服务\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("无法启动" + serviceName + "服务\n" + ex.Message);
            }
        }
        else { throw new Exception(" 不存在Window服务：" + serviceName); }
    }
    /// <summary>
    /// 停止window 服务
    /// </summary>
    /// <param name="serviceName">需要停止的服务名称</param>
    public static void StopService(string serviceName)
    {
        if (ServiceExisted(serviceName))//判断服务存在不
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                if (service.Status != ServiceControllerStatus.Running)
                {
                    service.Stop();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == ServiceControllerStatus.Stopped)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            throw new Exception("无法停止" + serviceName + "服务\n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("无法停止" + serviceName + "服务\n" + ex.Message);
            }
        }
        else { throw new Exception(" 不存在Window服务：" + serviceName); }
    }
}

